package main

import (
	"bufio"
	"fmt"
	"os"
	"regexp"
)

// 白名单列表，支持通配符
var whitelist = []string{
	"*.example.com",
	"*.test.com",
	"sub.*.domain.com",
}

// 从文件中读取白名单并返回正则表达式列表
func readWhitelistFromFile(filename string) ([]*regexp.Regexp, error) {
	file, err := os.Open(filename)
	if err != nil {
		return nil, fmt.Errorf("failed to open file: %v", err)
	}
	defer file.Close()

	var regexList []*regexp.Regexp
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		re, err := wildcardToRegex(line)
		if err != nil {
			fmt.Printf("Error compiling regex for pattern %s: %v\n", line, err)
			continue
		}
		regexList = append(regexList, re)
	}

	if err := scanner.Err(); err != nil {
		return nil, fmt.Errorf("error reading file: %v", err)
	}

	return regexList, nil
}

// 将通配符转换为正则表达式
func wildcardToRegex(pattern string) (*regexp.Regexp, error) {
	regex := "^" + regexp.QuoteMeta(pattern)
	regex = regexp.MustCompile(`\\\*`).ReplaceAllString(regex, ".*")
	regex += "$"
	return regexp.Compile(regex)
}

// 检查域名是否在白名单中
func isDomainInWhitelist(domain string) bool {
	for _, pattern := range whitelist {
		re, err := wildcardToRegex(pattern)
		if err != nil {
			fmt.Printf("Error compiling regex for pattern %s: %v\n", pattern, err)
			continue
		}
		if re.MatchString(domain) {
			return true
		}
	}
	return false
}

func main() {
	domainsToCheck := []string{"www.example.com", "notindomain.com", "test.test.com", "sub.anything.domain.com"}

	for _, domain := range domainsToCheck {
		if isDomainInWhitelist(domain) {
			fmt.Printf("Domain %s is in the whitelist.\n", domain)
		} else {
			fmt.Printf("Domain %s is NOT in the whitelist.\n", domain)
		}
	}
}
